﻿#region License
/*
The MIT License

Copyright (c) 2008 Sky Morey

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Security.Principal;
namespace System.DirectoryServices
{
    public static class Ldap
    {
        private static char[] _splitChars = new[] { '/' };

        //public static string MakeSafeForLdap(string original)
        //{
        //    var s = Regex.Replace(original, "[(]", "");
        //    s = Regex.Replace(s, "[)]", "");
        //    s = Regex.Replace(s, "&", "-");
        //    s = Regex.Replace(s, ",", "");
        //    s = Regex.Replace(s, "[.]", "");
        //    s = Regex.Replace(s, " ", "_");
        //    s = Regex.Replace(s, "__", "_");
        //    s = Regex.Replace(s, "__", "_");
        //    return s;
        //}

        //public static bool IsSafeLdapParameter(string queryParameter)
        //{
        //    var safe = new Regex(@"^[a-zA-Z0-9.@_\-\' $&#]*$");
        //    var symbols = new[] { " ", "'", "[.]" };
        //    var isSafe = true;
        //    foreach (var s in symbols)
        //    {
        //        var reg = s + s + "+";
        //        var doubleup = new Regex(reg);
        //        isSafe = (isSafe && !doubleup.IsMatch(queryParameter));
        //    }
        //    return (isSafe && safe.IsMatch(queryParameter));
        //}

        //public static bool PasswordMeetsComplexity(string password)
        //{
        //    int criteria = 0;
        //    //check lowercase
        //    var lowercase = new Regex("[a-z]");
        //    if (lowercase.IsMatch(password))
        //        criteria++;
        //    //check uppercase
        //    var uppercase = new Regex("[A-Z]");
        //    if (uppercase.IsMatch(password))
        //        criteria++;
        //    //check numbers
        //    var numeric = new Regex("[0-9]");
        //    if (numeric.IsMatch(password))
        //        criteria++;
        //    //check symbols
        //    var symbolic = new Regex(@"[.,@_\-\'$#!%^Z&*()+=?<>{}\[\]/\\:;|~`]");
        //    if (symbolic.IsMatch(password))
        //        criteria++;
        //    //must meet 3 of 4 criteria, plus be at least 7 characters long
        //    return (criteria >= 3 && password.Length >= 7);
        //}

        public static string TransformCNFromDN(string sourceDN, string targetDN)
        {
            return "CN=" + GetNameFromDN(sourceDN) + "," + targetDN;
        }

        public static string GetContainerFromDN(string dn)
        {
            if (string.IsNullOrEmpty(dn))
                throw new ArgumentNullException("dn");
            var startIndex = dn.IndexOf(',') + 1;
            return dn.Substring(startIndex);
        }

        public static string GetNameFromDN(string dn)
        {
            if (string.IsNullOrEmpty(dn))
                throw new ArgumentNullException("dn");
            var startIndex = dn.IndexOf('=') + 1;
            return dn.Substring(startIndex, dn.IndexOf(',') - startIndex);
        }

        public static string GetDNFromADsPath(string path)
        {
            var split = path.Split(_splitChars);
            return split[split.Length - 1];
        }

        internal static string GetPartitionFromDN(string defaultDN)
        {
            if (string.IsNullOrEmpty(defaultDN))
                throw new ArgumentNullException("defaultDN");
            var organizationIndex = defaultDN.IndexOf("O=", StringComparison.OrdinalIgnoreCase);
            if (organizationIndex > -1)
                return defaultDN.Substring(organizationIndex);

            var dcIndex = defaultDN.IndexOf("DC=", StringComparison.OrdinalIgnoreCase);
            if (dcIndex > -1)
                return defaultDN.Substring(dcIndex);

            throw new ArgumentOutOfRangeException("defaultDN", string.Format("Invalid DN '{0}'", defaultDN));
        }

        public static string EncodeFilter<T>(T value)
        {
            var valueAsSid = (value as SecurityIdentifier);
            if (valueAsSid != null)
                return EncodeFilter(valueAsSid);
            var valueAsBytes = (value as byte[]);
            if (valueAsBytes != null)
                return EncodeFilter(valueAsBytes);
            var valueAsString = (value as string);
            if (valueAsString != null)
                return EncodeFilter(valueAsString);
            return EncodeFilter(value.ToString());
        }
        public static string EncodeFilter(string value) { return EncodeFilter(value, true); }
        public static string EncodeFilter(string value, bool encodeWildcard)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;
            value = value.Replace(@"\", @"\5c").Replace("/", @"\2f").Replace("(", @"\28").Replace(")", @"\29").Replace("\0", @"\00");
            return (encodeWildcard ? value.Replace("*", @"\2a") : value);
        }
        public static string EncodeFilter(byte[] value)
        {
            if (value == null)
                return string.Empty;
            return @"\" + BitConverter.ToString(value).Replace("-", @"\");
        }
        public static string EncodeFilter(SecurityIdentifier value)
        {
            if (value == null)
                return string.Empty;
            var valueAsBytes = new byte[value.BinaryLength];
            value.GetBinaryForm(valueAsBytes, 0);
            return EncodeFilter(valueAsBytes);
        }

        public static string EncodeDistinguishedName(string value)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;
            return value.Replace("!", @"\21").Replace("*", @"\2A").Replace("/", @"\2F").Replace(":", @"\3A").Replace("?", @"\3F");
        }
    }
}
